package com.aaa.gs.config;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @ fileName:MyRandomRule
 * @ description:
 * @ author:zhz
 * @ createTime:2021/1/12 11:04
 */
@SuppressWarnings("all")
public class MyRandomRule extends AbstractLoadBalancerRule {
    public MyRandomRule() {
    }

    /**
     * 负载均衡服务器选择方法
     * @param lb
     * @param key
     * @return
     */
    //@SuppressWarnings({"RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE"})
    public Server choose(ILoadBalancer lb, Object key) {
        // ILoadBalancer ribbon客户端从注册中心获取的所有参与负载均衡服务的信息
        System.out.println("lb开始："+lb+"....结束");
        //int a=0;
        if (lb == null) {
            return null;
        } else {
            Server server = null;

            while(server == null) {
                //判断线程是否中断
               /*Thread t1= new Thread();
                if(t1.isInterrupted()){
                }*/
                if (Thread.interrupted()) {
                    return null;
                }
                //获取可用服务器
                List<Server> upList = lb.getReachableServers();
                System.out.println("在线（可用）服务列表为："+upList);
                //获取所有服务器
                List<Server> allList = lb.getAllServers();
                System.out.println("所有服务器=列表为："+allList);
                int serverCount = allList.size();
                System.out.println("所有服务总数量"+serverCount);
                if (serverCount == 0) {
                    return null;
                }
                 //选择服务器  serverCount =3
                int index = this.chooseRandomInt(serverCount);
                System.out.println("选择的服务编号为"+index);
                //根据编号获取真正服务器
                server = (Server)upList.get(index);
                if (server == null) {
                    //yield  当前线程让出CPU，让其他线程执行
                    Thread.yield();
                } else {
                    // isAlive 再次判断服务器是否存货
                    if (server.isAlive()) {
                        return server;
                    }

                    server = null;
                    Thread.yield();
                }
            }

            return server;
        }
    }

    protected int chooseRandomInt(int serverCount) {
        //new Random().nextInt(3);//得到0-2的数字  线程不安全
        return ThreadLocalRandom.current().nextInt(serverCount);////得到0-2的数字  线程安全
    }

    public Server choose(Object key) {
        return this.choose(this.getLoadBalancer(), key);
    }

    public void initWithNiwsConfig(IClientConfig clientConfig) {
    }

    public static void main(String[] args) {
        //nextInt   [0,3)  一个随机数
        System.out.println(ThreadLocalRandom.current().nextInt(3));
    }
}
